import Vue from 'vue'
import App from './App.vue'
import router from './router' //自动会去查询index.js文件
import store from './store'
import '@/assets/css/style.css'
import axios from 'axios'
import { MessageBox, Message } from 'element-ui';

// 全局挂载
Vue.prototype.$messageBox = MessageBox
Vue.prototype.$message = Message;

// 在应用初始化时检查sessionStorage并恢复状态
const firstLevelList = JSON.parse(sessionStorage.getItem('firstLevelList'));
const levelMap = JSON.parse(sessionStorage.getItem('levelMap'));
if (firstLevelList) {
  store.commit('SET_FIRST_LEVEL_LIST', firstLevelList);
}
if (levelMap) {
  store.commit('SET_LEVEL_MAP', levelMap);
}



import { Table, TableColumn, Button, Popover, Form, FormItem, Input, Dialog,Radio,RadioGroup,Cascader} from 'element-ui'
Vue.component(Button.name, Button)
Vue.component(Form.name, Form)
Vue.component(FormItem.name, FormItem)
Vue.component(Input.name, Input)
Vue.component(Dialog.name, Dialog)
Vue.component(Radio.name, Radio)
Vue.component(RadioGroup.name, RadioGroup)
Vue.component(Cascader.name, Cascader)
Vue.use(Table)
Vue.use(Button)
Vue.use(Popover)
Vue.use(TableColumn)

// 挂载到 Vue 原型，方便全局调用 this.$axios
Vue.prototype.$axios = axios
Vue.config.productionTip = false
Vue.prototype.$http = axios


// axios前置拦截器
axios.interceptors.request.use(config=>{
  //在所有请求中加入认证token
  let token = window.sessionStorage.getItem('token')
  if(token != null){
    config.headers['Authorization'] = token
  }
  return config
},error=>{
  Promise.reject(error)
})
//axios后置拦截器
axios.interceptors.response.use(response=>{
  //当token快过期时，后台会进行延期处理，生成新的token，前台需更换新的token
  let refToken = response.headers['x-token']
  if(refToken){
    //如果有新的token，则替换原有token
    window.sessionStorage.setItem('token',refToken);
    console.log("token续期...")
  }
  console.log("后置拦截",response)
  return response
},error=>{
  console.log('后置拦截错误',error.response.data)
  //统一处理服务端的报错
  if(error.response){
    if(error.response.data.msg == "登录超时") {
      MessageBox.alert(error.response.data.msg);
      window.sessionStorage.removeItem("type");
      window.sessionStorage.removeItem("token");
      window.sessionStorage.removeItem("loginName");
      Message.error("登录超时")
      window.location.reload(); // 关键点！
      // router.push("/Authentication/Login").catch(() => {})
        // store.commit("clearAuth")
      }
      if(error.response.data.msg == "权限不足") {
        Message.error("权限不足！将返回到首页")
        router.push({name: 'IndexCenter'}).catch(() => {})
    }
  }
  
  return Promise.reject(error);
})

//文件访问地址
// let imagesDir = 'http://10.18.1.14:5050/images/' 
let imagesDir = 'http://192.168.137.236:5050/images/'
sessionStorage.setItem("imagesDir", imagesDir);

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app')
